package org.wanho.sms.service.proxy;

import java.util.List;

import org.wanho.sms.entity.Student;
import org.wanho.sms.exception.ServiceException;
import org.wanho.sms.exception.StudentNameExistsException;
import org.wanho.sms.exception.StudentNotFoundException;
import org.wanho.sms.factory.ObjectFactory;
import org.wanho.sms.service.StudentService;
import org.wanho.sms.transaction.TransactionManager;

public class StudentServiceProxy implements StudentService{
	
	private TransactionManager tx = (TransactionManager) ObjectFactory.getObject("tx");
	private StudentService studentService = (StudentService) ObjectFactory.getObject("studentService");

	@Override
	public List<Student> findAll() {
		List<Student> list = null;
		try {
			tx.beginTransaction();
			list = studentService.findAll();
			tx.commit();
		} catch (Exception e) {
			tx.rollback(); 
			throw new ServiceException("服务异常",e);
		}
		return list;
	}

	@Override
	public Student findById(int id) {
		Student stu = studentService.findById(id);
		return stu;
	}

	@Override
	public void modify(Student stu) {
		studentService.modify(stu);
	}

	@Override
	public void add(Student stu) throws StudentNameExistsException {
		studentService.add(stu);
	}

	@Override
	public void removeById(int id) {
		try {
			tx.beginTransaction();
			studentService.removeById(id);
			tx.commit();
		} catch (Exception e) {
			tx.rollback(); 
			throw new ServiceException("服务异常",e);
		}
	}

	@Override
	public void swap(String name1, String name2)
			throws StudentNotFoundException {
		try {
			tx.beginTransaction(); // 开启事务
			studentService.swap(name1, name2);
			tx.commit(); // 提交事务
		} catch (Exception e) {
			tx.rollback(); // 回滚事务
			throw new ServiceException("服务异常",e);
		}
	}

}
